var vie_race_edit = vie_fwk_base_page.extend({
    tagName: 'div',
    race: null,
    initialize: function(options){
        this.initVars(options);
        $('a#current-section').html('Races');
        this.pageHeadModel.setToolbarId(this.getContainerId());
        if(this.options.race != null){
            this.pageHeadModel.set('title', 'Edit Race')
            this.pageHeadModel.set('description', '');
            this.race = __app.colls.races.get(this.options.race);
        }else{
            this.pageHeadModel.set('title', 'Add A Race');
            this.pageHeadModel.set('description', '');
            this.race = new mod_race();
        }
        this.pageHeadModel.addButton('icon-list', 'My Races', '#races');
    },
    render: function(){
        this.pageBody = new vie_race_edit_form({model: this.race, collection: new coll_fwk_base_form_fields()});
        this.displayToMain();
        this.pageBody.postRender();
        return this;
    }
});


var vie_race_edit_form = vie_fwk_base.extend({
    tagName: 'div',
    className: 'well',
    fieldsCont: null,
    formView: null,
    formModel: null,
    fieldNameSpace: null,
    initialize: function(){
        this.fieldNameSpace = 'race-edit-form-field'+(typeof this.model.get('id') != 'undefined'?('-' + this.model.get('id')): '') + '-';
        var that = this;
        var onSubmit = function(){
            that.formSubmit.apply(that, arguments);
        };
        this.formModel = new mod_fwk_base_form({
            formId: 'race-edit-form' + (typeof this.model.get('id') != 'undefined'?('-' + this.model.get('id')): ''),
            onSubmit: onSubmit
        });
        this.setFormFields();
    },
    render: function(){
        this.formView = new vie_fwk_base_form({model: this.formModel, collection: this.collection});
        $(this.el).html(this.formView.render().el);
        return this;    
    },
    postRender: function(){
        var context = this.$el;
        $("select", context).mobiscroll().select({ 
            theme: 'sense-ui',
            display: 'modal',
            mode: 'scroller',
            width: 200, 
            inputClass: 'input-xlarge'
        });
        $('input[id$="_dummy"]', context).removeAttr('readonly');
        $("input[type='date']", context)
                                        .attr('type', 'text')
                                        .mobiscroll()
                                        .date({ 
                                            mode: 'mixed',
                                            theme: 'sense-ui', 
                                            display: 'modal', 
                                            dateFormat: 'mm/dd/yy'
                                         }).removeAttr('readonly');
        $('textarea', context).autogrow();  
        $("select[data-type='multiselect']", context).multiSelect({placeholder: 'select entries from here'});
    },
    formSubmit: function(formObj, ev){
        ev.preventDefault();
        var formVals = formObj.getValues();
        var submitVals = {};
        _.each(formVals, function(val, key){
                var fieldName = key.replace(this.fieldNameSpace, '');
                if(key != this.fieldNameSpace + 'save-button' && key != this.fieldNameSpace + 'active'){
                    if(fieldName == 'date'){
                        try{
                            submitVals[fieldName] = val.getTime();
                        }catch(e){
                            submitVals[fieldName] = new Date(val).getTime();
                        }
                    }else if(fieldName == 'entries'){
                        var arr = new Array();
                        _.each(val, function(val, key){
                            arr.push(key);
                        });
                        submitVals[fieldName] = arr;
                    }else{
                        submitVals[fieldName] = val;
                    }
                }
        }, this);
        this.model.set(submitVals);
        this.model.setDateMod();
        //this.model.save();
        
        if(typeof this.model.validationError != 'undefined' && this.model.validationError != null && this.model.validationError.length > 0){
            _.each(this.model.validationError, function(errorObj){
                var fieldId = this.fieldNameSpace + errorObj.name;
                var field = $('#' + fieldId, this.$el);
                field.parent().parent().addClass('error');
                var fieldHelpBlock = field.parent().find('p.help-block');
                fieldHelpBlock.html(errorObj.message);
            }, this);
        }else{
            if(typeof this.model.get('id') == 'undefined') __app.colls.races.create(this.model);
            __app.router.navigate('races', {trigger: true, replace: false});
        }
    },
    fieldChange: function(formFieldObj, ev){
        if(formFieldObj.$el.hasClass('error')){
            formFieldObj.$el.find('p.help-block').html('');
            formFieldObj.$el.removeClass('error');
        }
        
        
    },
    setFormFields: function(){
        var that = this;
        var onFieldChange = function(){
            that.fieldChange.apply(that, arguments);
        }
        // 'name': 'race ' + new Date().format('fullDate'),
            // 'venue': 'somewhere',
            // 'date': new Date().getTime(),
            // 'note': 'none',
            // 'cars': new Array(),
            // 'entries': new Array(),
            // 'result': 'on-going',
            // 'type': 'technical',
            // 'dateCreate': new Date().getTime(),
            // 'dateMod': new Date().getTime(),
            // 'active': true
        //label, type, value, name, selectOptions, onChange
        var raceDate = new Date(this.model.get('date')).format("mm/d/yyyy");
        //name
        this.collection.addField('race name<i class="icon-asterisk"></i>', 'text', this.model.get('name'), this.fieldNameSpace + 'name', null, onFieldChange); 
        //venue
        this.collection.addField('race venue<i class="icon-asterisk"></i>', 'text', this.model.get('venue'), this.fieldNameSpace + 'venue', null, onFieldChange); 
        //date
        this.collection.addField('date', 'date', raceDate, this.fieldNameSpace + 'date', null, null); 
        //cars 
        //TODO: add option to add a entry here directly
        //this.collection.addField('notes', 'textarea', this.model.get('note').key, this.fieldNameSpace + __app.getList('brakeTypes'), null, null); 
        //entries
        //TODO: add option to add a entry here directly
        //this.collection.addField('race entries', 'multiselect', this.model.get('entries'), this.fieldNameSpace + 'entries', __app.getList('cars_db'), null); 
        //result
        this.collection.addField('result', 'select', this.model.get('result').key, this.fieldNameSpace + 'result', __app.getList('raceResultTypes'), null); 
        //type
        this.collection.addField('race type', 'select', this.model.get('type').key, this.fieldNameSpace + 'type', __app.getList('raceTypes'), null); 
        //note
        this.collection.addField('race notes', 'textarea', this.model.get('note'), this.fieldNameSpace + 'note', null, null); 
        //active
        this.collection.addField('set as active race?', 'checkbox', false, this.fieldNameSpace + 'active', null, null); 
        //save 
        this.collection.addField(null, 'button', 'save', this.fieldNameSpace + 'save-button', new Array(), null);
    }
});
